# coding=utf-8

'''主机管理'''
import json
import uuid

from datetime import datetime
from django.http import HttpResponse
from django.shortcuts import render

from dockerManagerApp import models
from dockerManagerApp.model import images_manager
from dockerManagerApp.model.base.rpc_client import rpcClientFunction


def update_node_status_fun():
    listValue = models.HostManager.objects.filter().values()
    for i in range(len(listValue)):
        uuid = listValue[i].get('uuid')
        hostaddr = listValue[i].get('hostaddr')
        db_status = listValue[i].get('status')

        # status 是获取主机状态的变量
        try:
            arg_dict = {}
            rpclient = rpcClientFunction(hostaddr)
            retu = rpclient.updateHostStatus(arg_dict)
            if retu.get('status') == True:
                status = "0"
            else:
                status = "1"
        except:
            status = "1"
        if db_status != status:
            # 查询数据库结果和执行结果不一样则更新数据库
            print('查询数据库结果和执行结果不一样则更新数据库')
            models.HostManager.objects.filter(uuid=uuid).update(status=status)
        else:
            pass
            # print('the samed ... ')


def imageManager(request):
    action = request.POST.get("action")
    if action == 'import':
        return images_manager.import_image(request)
    elif action == 'del':
        return images_manager.del_image(request)
    elif action == 'localcreate':
        return images_manager.create_local_image(request)
    elif action == 'dockerpullcreate':
        return images_manager.docker_pull_image(request)

def item_host_info(request, nid):
    listValue = models.HostManager.objects.filter(uuid=nid).values()

    hostInfoDict = {}

    for i in range(len(listValue)):
        hostInfoDict['hostname'] = listValue[i].get('hostname')
        hostInfoDict['uuid'] = listValue[i].get('uuid')
        hostInfoDict['addtimer'] = listValue[i].get('addtimer')
        hostInfoDict['hostdesc'] = listValue[i].get('hostdesc')
        hostinfojson = json.loads(listValue[i].get('hostinfo'))

        hostInfoDict['NCPU'] = hostinfojson.get('NCPU')
        hostInfoDict['OperatingSystem'] = hostinfojson.get('OperatingSystem')
        hostInfoDict['MemTotal'] = hostinfojson.get('MemTotal')
        hostInfoDict['KernelVersion'] = hostinfojson.get('KernelVersion')

    hostinfo = []
    hostinfo.append(hostInfoDict)
    print(hostinfo)
    return render(request, 'itemhostinfo.html', {'hostinfo': hostinfo})


def get_all_host(request, retuType=0):
    host_list = []
    # return render(request, 'terminal_list.html', {"terminal_list": listAll})

    listValue = models.HostManager.objects.filter().values()
    for i in range(len(listValue)):
        uuid = listValue[i].get('uuid')
        hostname = listValue[i].get('hostname')
        hostaddr = listValue[i].get('hostaddr')
        hostdesc = listValue[i].get('hostdesc')
        addtimer = listValue[i].get('addtimer')
        status = listValue[i].get('status')
        print(status)

        # status 是获取主机状态的变量
        # try:
        #     arg_dict = {}
        #     rpclient = rpcClientFunction(hostaddr)
        #     retu = rpclient.updateHostStatus(arg_dict)
        #     if retu.get('status') == True:
        #         status = "0"
        #     else:
        #         status = "1"
        # except:
        #     status = "1"

        item_value = {
            'count': i + 1,
            'uuid': uuid,
            'hostname': hostname,
            'hostaddr': hostaddr,
            'hostdesc': hostdesc,
            'addtimer': addtimer,
            'status': status
        }
        host_list.append(item_value)

    # print(listValue)
    if retuType == 0:
        return render(request, 'hostmanager.html', {'host_list': host_list})
    else:
        ret = {'status': True, 'error': None, 'data': None}
        ret['data'] = host_list;
        print(host_list)
        return HttpResponse(json.dumps(ret))


def action_host(request):
    '''添加主机功能'''
    ret = {'status': False, 'error': None, 'data': None}
    if request.method == 'POST':
        action = request.POST.get("action")
        if action == 'add':
            hostname = request.POST.get("host_name")
            hostaddr = request.POST.get("host_addr")
            hostdesc = request.POST.get("host_desc")

            arg_dict = {'action': action,
                        'hostname': hostname,
                        'hostaddr': hostaddr,
                        'hostdesc': hostdesc,
                        }
            rpclient = rpcClientFunction(hostaddr)
            try:
                retu = rpclient.updateHostStatus(arg_dict)
                if retu['status'] == True:
                    '''在这里添加添加主机的功能函数'''

                    # 检查是否有重复添加的主机-top
                    listValue = models.HostManager.objects.filter(hostname=hostname).values('hostname')
                    for item in listValue:
                        if item.get('hostname') == hostname:
                            ret = {'status': False, 'error': '该主机已经存在!', 'data': None}
                            return HttpResponse(json.dumps(ret))
                    # 检查是否有重复添加的主机-end

                    status = '0'  # 默认为启用状态
                    current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    hostinfo = retu['data']
                    print(hostinfo)
                    models.HostManager.objects.create(uuid=uuid.uuid1(),
                                                      hostname=hostname,
                                                      hostaddr=hostaddr,
                                                      hostdesc=hostdesc,
                                                      addtimer=current_time,
                                                      hostinfo=hostinfo,
                                                      status=status)

                    listValue = models.HostManager.objects.filter(hostname=hostname).values('hostname')
                    for item in listValue:
                        if item.get('hostname') == hostname:
                            ret = {'status': True, 'error': None, 'data': None}
                            break

                else:
                    return {'status': False, 'error': '主机连接状态不正常', 'data': None}
            except:
                ret['status'] = False
                ret['error'] = '无法连接到主机'
                ret['data'] = None

            return HttpResponse(json.dumps(ret))

        elif action == 'stop':
            uuidv = request.POST.get("uuid")
            models.HostManager.objects.filter(uuid=uuidv).update(status='1')
            ret = {'status': True, 'error': None, 'data': None}
            return HttpResponse(json.dumps(ret))

        elif action == 'start':
            uuidv = request.POST.get("uuid")
            models.HostManager.objects.filter(uuid=uuidv).update(status='0')
            ret = {'status': True, 'error': None, 'data': None}
            return HttpResponse(json.dumps(ret))


        elif action == 'del':
            '''在这里添加删除主机的操作'''
            uuidv = request.POST.get("uuid")
            models.HostManager.objects.filter(uuid=uuidv).delete()
            ret = {'status': True, 'error': None, 'data': None}
            return HttpResponse(json.dumps(ret))
